#include "platform.h"
#include "commapi.h"
//16 is engough for most situations
#define MAX_COMM_MODULE_NUM 16
static ST_COMM_MODULE comm_intfs[MAX_COMM_MODULE_NUM]={0};

static PST_COMM_MODULE find_available_location(void){
	int i;
	for(i=0;i<MAX_COMM_MODULE_NUM;i++){
		if(!comm_intfs[i].comm_prot)
			return &comm_intfs[i];
	}
	return NULL;
}

PST_COMM_MODULE find_comm_module_by_proto(const char* proto){
	int i;
	for(i=0;i<MAX_COMM_MODULE_NUM;i++){
		if(NULL==comm_intfs[i].comm_prot) break;
		if(!strcmp(comm_intfs[i].comm_prot,proto))
			return &comm_intfs[i];
	}
	return NULL;
}

PST_COMM_MODULE find_comm_module_by_library(const char* commlib){
	int i;
	int complen = 0;
	if(!commlib) return NULL;
	
	for(i=0;i<MAX_COMM_MODULE_NUM;i++){
        if(NULL==comm_intfs[i].comm_lib) break;
        complen = (strlen(comm_intfs[i].comm_lib)>strlen(commlib))?
        strlen(commlib):strlen(comm_intfs[i].comm_lib);
		if(!strncmp(comm_intfs[i].comm_lib,commlib,complen))
			return &comm_intfs[i];
	}
	return NULL;
}

int install_comm_module(PST_COMM_MODULE module){
	PST_COMM_MODULE oldintf = find_comm_module_by_proto(module->comm_prot);
	PST_COMM_MODULE myintf = find_available_location();
	if(oldintf){
		UDK_LOGW("comm interface %s already installed\n",module->comm_prot);		
	}else if(module&&myintf){
		//just copy
        UDK_LOGI("register %s module\n", module->comm_prot);
		memcpy(myintf,module,sizeof(ST_COMM_MODULE));
		myintf->comm_prot = strdup(module->comm_prot);
		if(strlen(module->comm_lib))
			myintf->comm_lib = strdup(module->comm_lib);
		return 0;
	}
	return -1;
}
int uninstall_comm_module(const char* comm_prot){
  int i;
  for(i=0;i<MAX_COMM_MODULE_NUM;i++){
    if(NULL==comm_intfs[i].comm_prot) break;
      if(!strcmp(comm_intfs[i].comm_prot,comm_prot)){
	free((void*)comm_intfs[i].comm_prot);
	if(comm_intfs[i].comm_lib) free((void*)comm_intfs[i].comm_lib);
	memset(&comm_intfs[i],0,sizeof(ST_COMM_MODULE));
	return 0;
      }
  }
  return -1;
}
int free_comm_modules(void){
  int i;
  for(i=0;i<MAX_COMM_MODULE_NUM;i++){
    if(comm_intfs[i].comm_prot) free((void*)comm_intfs[i].comm_prot);
    if(comm_intfs[i].comm_lib) free((void*)comm_intfs[i].comm_lib);
  }
  return 0;
}

